/********************************************************************
	created:	2012/4/11
	filename: 	AppMain.cpp
	author:		Mwolf
	
	purpose:	
*********************************************************************/

#include "Renderer/GWRenderWindow.h"
#include "Renderer/GWRenderDevice.h"
#include "GWTimer.h"

#include "Box2D/Box2D.h"

#include <windows.h>

static int ScreenWidth = 640, ScreenHeight = 480;


#if defined GW_PLATFORM_WIN32
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
#else
int main()
#endif
{
	// Create render window
	GW_RENDER_WINDOW* rw = GWWnd_CreateRenderWindow( ScreenWidth, ScreenHeight, "Box2d Test");

	RenderSystem::Initialize( rw );

	// Create box2d world
	b2Vec2 gravity( 0.f, -10.f );

	b2World world(gravity);

	// Creating a ground box
	b2BodyDef groundBodyDef;
	groundBodyDef.position.Set( 0.f,  -10.f );

	b2Body* groundBody = world.CreateBody( &groundBodyDef );

	b2PolygonShape groundBox;
	groundBox.SetAsBox( 50.f, 10.f );

	groundBody->CreateFixture( &groundBox, 0.f );

	// Creating a dynamic body
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	bodyDef.position.Set( 0.f, 50.f );
	b2Body* body = world.CreateBody( &bodyDef );

	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox( 1.f, 1.f );

	b2FixtureDef fixtureDef;
	fixtureDef.shape = &dynamicBox;
	fixtureDef.density = 1.f;
	fixtureDef.friction = .3f;
	body->CreateFixture( &fixtureDef );

	float32 timeStep = 1.f / 30.f;

	int32 velocityIterations = 6;
	int32 positionIterations = 2;

	while ( HandleWindowMessage() )
	{
		world.Step( timeStep, velocityIterations, positionIterations );

		RenderSystem::BeginRender();
		RenderSystem::SetViewport( 0, 0, ScreenWidth, ScreenHeight );

		RenderSystem::SetOrthoProjMatrix( ScreenWidth, ScreenHeight, 0.1f, 100.f );
		RenderSystem::SetViewMatrix( Vector3(0.f, 0.f, -5.f), Vector3::ZERO );

		RenderSystem::Clear(GWColor(.5f, .5f, 1.f));

		float t = .001f * (float)GWSys_GetTickCount();
		float a = sinf(t),
			  b = cosf(t);

		RenderSystem::DrawLine( Vector3(-100.f * a, -100.f * b, 0.f), Vector3(100.f * a, 100.f * b, 0.f) );

		b2Vec2 b2BoxPos = body->GetPosition();
		Vector2 boxPos = Vector2( b2BoxPos.x, b2BoxPos.y );
		RenderSystem::DrawWireframeRect( boxPos + Vector2(10.f, 10.f), boxPos - Vector2(10.f, 10.f) );

		RenderSystem::EndRender();

		RenderSystem::Flush();
	}

	// Shut down and destroy device
	RenderSystem::Destroy();
	GWWnd_DestroyRenderWindow( rw );

	return 0;
}
